//
//  GLLocalFileStore.m
//  ECERP_Car
//
//  Created by huanggulong on 16/3/3.
//  Copyright © 2016年 com.mamizx. All rights reserved.
//

#import "GLLocalFileStore.h"
#import <AssetsLibrary/AssetsLibrary.h>

#import <Photos/Photos.h>
#import "GLLocalFilePath.h"

@implementation GLLocalFileStore


+ (NSMutableArray *)savePhotos:(NSMutableArray *)photos{
    NSMutableArray *array = [NSMutableArray array];
    [photos enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        ALAsset *representation = obj;
        
        GLLocalFile *fileModel = [[GLLocalFile alloc] init];
        fileModel.thumbnail = [UIImage imageWithCGImage:representation.thumbnail];
        UIImage *image = [UIImage imageWithCGImage:representation.defaultRepresentation.fullResolutionImage
                                           scale:representation.defaultRepresentation.scale
                                     orientation:(UIImageOrientation)representation.defaultRepresentation.orientation];
        //                fileModel.origin = img;
        UIImage *img = [self fixOrientation:image];
        fileModel.resolution = [NSString stringWithFormat:@"%.0fx%.0f",img.size.width,img.size.height];
        NSString *url = [[[GLLocalFilePath getTempPath]  stringByAppendingPathComponent:[self fileNameWithTodayAndNow] ] stringByAppendingString:@".jpg"];
        [UIImageJPEGRepresentation(img, 0.5) writeToFile:url atomically:YES];
        fileModel.fileURL = url;
        fileModel.fileExtension = @"jpg";
        fileModel.fileName = [[representation.defaultRepresentation.filename componentsSeparatedByString:@"."] firstObject];
//        fileModel.asset = representation;
        [array addObject:fileModel];
    }];
    return array;
}

+ (GLLocalFile *)saveImage:(UIImage *)image{
    UIImage *img = [self fixOrientation:image];
    GLLocalFile *model = [[GLLocalFile alloc] init];
    model.resolution = [NSString stringWithFormat:@"%.0fx%.0f",img.size.width,img.size.height];
    model.fileName =[self fileNameWithDate:[NSDate date]];
    NSString *url = [[[GLLocalFilePath getTempPath]  stringByAppendingPathComponent:model.fileName]stringByAppendingString:@".jpg"];
    [UIImageJPEGRepresentation(img, 0.5) writeToFile:url atomically:YES];
    model.fileURL = url;
    model.fileExtension = @"jpg";
    model.thumbnail = [image gl_scaleImageWithMaxLength:320];
    return model;
}

+ (void)saveVideo:(id)video success:(void (^)(GLLocalFile *))success failure:(void (^)(NSError *))failure{
    if ([video isKindOfClass:[ALAsset class]]) {
        [self saveALVideo:video success:success failure:failure];
    }else if ([video isKindOfClass:[PHAsset class]]){
        [self savePHVideo:video success:success failure:failure];
    }
    
}

+ (void)saveALVideo:(ALAsset *)video success:(void (^)(GLLocalFile *))success failure:(void (^)(NSError *))failure{
    GLLocalFile *fileModel = [[GLLocalFile alloc] init];
    UIImage *img = [UIImage imageWithCGImage:video.defaultRepresentation.fullResolutionImage
                                       scale:video.defaultRepresentation.scale
                                 orientation:(UIImageOrientation)video.defaultRepresentation.orientation];
    fileModel.origin = img;
    fileModel.thumbnail = [UIImage imageWithCGImage:video.thumbnail];
    
    
    ALAssetRepresentation *representation = video.defaultRepresentation;
    NSURL *movieURL = representation.url;
    NSString *str = [video valueForProperty:ALAssetPropertyDuration];
    NSString *urlString = [[[GLLocalFilePath getTempPath] stringByAppendingPathComponent:[self fileNameWithDate:[NSDate date]]] stringByAppendingString:@".mp4"];
    NSURL *uploadURL = [NSURL fileURLWithPath:urlString];
    AVAsset *asset      = [AVURLAsset URLAssetWithURL:movieURL options:nil];
    AVAssetExportSession *session =
    [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
    
    session.outputFileType  = AVFileTypeMPEG4;
    session.outputURL       = uploadURL;
    
    __block GLLocalFile *weakModel = fileModel;
    [session exportAsynchronouslyWithCompletionHandler:^{
        
        weakModel.fileURL = urlString;
        weakModel.fileExtension = @"mp4";
        weakModel.totalTime = str;
        if (session.status == AVAssetExportSessionStatusCompleted)
        {
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    success(weakModel);
                });
            }
        }else if(session.status == AVAssetExportSessionStatusFailed){
            if (failure) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    failure(session.error);
                });
            }
        }
    }];
}

+ (void)savePHVideo:(PHAsset *)video success:(void (^)(GLLocalFile *))success failure:(void (^)(NSError *))failure{
    if (failure) {
        NSError *error = [NSError errorWithDomain:@"com.mamizx" code:9124 userInfo:nil];
        failure(error);
    }
//    GLLocalFile *fileModel = [[GLLocalFile alloc] init];
//    UIImage *img = [UIImage imageWithCGImage:video.defaultRepresentation.fullResolutionImage
//                                       scale:video.defaultRepresentation.scale
//                                 orientation:(UIImageOrientation)video.defaultRepresentation.orientation];
//    fileModel.origin = img;
//    fileModel.thumbnail = [UIImage imageWithCGImage:video.thumbnail];
}


+ (UIImage *)fixOrientation:(UIImage *)aImage{
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


//@private
+(NSString *)fileNameWithTodayAndNow{
    return [self fileNameWithDate:[NSDate date]];
}

+(NSString *)fileNameWithDate:(NSDate *)date{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmssSSSS";
    return [formatter stringFromDate:date];
}

@end
